package com.chenshu.validator;

import com.chenshu.domain.LoginUser;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-04-29
 * Time：16:47
 */
@Component
public class LoginUserValidator implements Validator {

    //判断是否是LoginUser的类型或子类
    @Override
    public boolean supports(Class<?> aClass) {
        return LoginUser.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        LoginUser loginUser = (LoginUser) o;
        if (loginUser.getUsername() == null || loginUser.getUsername().trim().isEmpty()) {
            errors.rejectValue("username", "loginUser.username.required");
        }
        if (loginUser.getPassword() == null || loginUser.getPassword().trim().isEmpty()) {
            errors.rejectValue("password", "loginUser.password.required");
        }
        if (loginUser.getUsername() != null && !loginUser.getUsername().isEmpty()) {
            int len = loginUser.getUsername().trim().length();
            System.out.println(loginUser.getUsername() + ",len=" + len);
            if (len < 6 || len > 12) {
                errors.rejectValue("username", "loginUser.username.invalid");
            }
        }
        if (loginUser.getPassword()!=null && !loginUser.getPassword().trim().isEmpty()) {
            int len = loginUser.getPassword().trim().length();
            if (len < 6) {
                errors.rejectValue("password", "loginUser.password.invalid");
            }
        }
    }
}
